<template>
  <div class="page-wrap">
    <a-card title="角色管理" :bordered="false">
      <template #extra>
        <a-space>
          <a-input v-model="query.roleName" placeholder="角色名" allow-clear style="width: 160px" />
          <a-input v-model="query.roleCode" placeholder="角色编码" allow-clear style="width: 160px" />
          <a-button type="primary" @click="fetchList">查询</a-button>
          <a-button @click="resetQuery">重置</a-button>
          <a-button type="primary" status="success" @click="openEdit">新增</a-button>
        </a-space>
      </template>

      <!-- 修改为使用 columns 属性定义列 -->
      <a-table
          row-key="roleId"
          :data="tableData"
          :columns="columns"
          :loading="loading"
      />
    </a-card>

    <!-- 新增/编辑模态框保持不变 -->
    <a-modal v-model:visible="editVisible" :title="editing?.roleId ? '编辑角色' : '新增角色'" :mask-closable="false" @ok="saveRole" :confirm-loading="saving">
      <a-form :model="editing" layout="vertical">
        <a-form-item field="roleName" label="角色名" :rules="[{ required: true, message: '请输入角色名' }]">
          <a-input v-model="editing.roleName" />
        </a-form-item>
        <a-form-item field="roleCode" label="编码" :rules="[{ required: true, message: '请输入编码' }]">
          <a-input v-model="editing.roleCode" />
        </a-form-item>
        <a-form-item field="sort" label="排序">
          <a-input-number v-model="editing.sort" :min="0" />
        </a-form-item>
        <a-form-item field="remark" label="备注">
          <a-textarea v-model="editing.remark" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 分配菜单模态框保持不变 -->
    <a-modal v-model:visible="assignVisible" title="分配菜单" :mask-closable="false" @ok="submitAssignMenus" :confirm-loading="assignSaving" :width="640">
      <a-spin :loading="assignLoading">
        <a-tree
            checkable
            :data="menuTree"
            v-model:checked-keys="checkedMenuIds"
            :field-names="{ key: 'menuId', title: 'menuName', children: 'children' }"
        />
      </a-spin>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { Message } from '@arco-design/web-vue';
import type { SysRole, SysMenu } from '@/types/system';
import { roleList, roleAdd, roleUpdate, roleDelete, roleAssignMenus, roleGet } from '@/api/role';
import { menuList } from '@/api/menu';

const query = reactive<{ roleName?: string; roleCode?: string }>({ roleName: '', roleCode: '' });
const loading = ref(false);
const rows = ref<SysRole[]>([]);

// 使用 computed 确保数据格式正确
const tableData = computed(() => {
  return rows.value.map(row => ({
    roleId: row.roleId || 0,
    roleName: row.roleName || '',
    roleCode: row.roleCode || '',
    sort: row.sort !== undefined ? row.sort : 0
  }));
});

// 使用 columns 配置定义表格列
const columns = computed<TableColumns<SysRole>>(() => [
  {
    title: 'ID',
    dataIndex: 'roleId',
    width: 100
  },
  {
    title: '角色名',
    dataIndex: 'roleName'
  },
  {
    title: '编码',
    dataIndex: 'roleCode'
  },
  {
    title: '排序',
    dataIndex: 'sort',
    width: 100
  },
  {
    title: '操作',
    width: 260,
//     render: (_, record) => (
//         <a-space>
//         <a-button type="text" onClick={() => openEdit(record)}>编辑</a-button>
// <a-button type="text" status="warning" onClick={() => openAssignMenus(record)}>分配菜单</a-button>
// <a-popconfirm content="确认删除该角色？" onOk={() => onDelete(record)}>
// <a-button type="text" status="danger">删除</a-button>
//     </a-popconfirm>
//     </a-space>
// )
  }
]);

// 优化数据获取逻辑
async function fetchList() {
  loading.value = true;
  try {
    const res = await roleList(query);
    // 确保数据格式正确
    rows.value = Array.isArray(res.data) ? res.data : [];
  } catch (error) {
    console.error('获取角色列表失败:', error);
    Message.error('获取角色列表失败');
    rows.value = [];
  } finally {
    loading.value = false;
  }
}

function resetQuery() {
  query.roleName = '';
  query.roleCode = '';
  fetchList();
}

// 优化编辑表单对象类型定义
const editVisible = ref(false);
const saving = ref(false);
const editing = reactive<{ roleId?: number; roleName: string; roleCode: string; sort: number; remark?: string }>({
  roleName: '',
  roleCode: '',
  sort: 0
});

function openEdit(row?: SysRole) {
  editVisible.value = true;
  if (row?.roleId) {
    Object.assign(editing, row);
    // 确保 sort 有默认值
    if (editing.sort === undefined) editing.sort = 0;
  } else {
    Object.assign(editing, { roleId: undefined, roleName: '', roleCode: '', sort: 0, remark: '' });
  }
}

async function saveRole() {
  saving.value = true;
  try {
    if (editing.roleId) {
      await roleUpdate(editing);
      Message.success('已保存');
    } else {
      await roleAdd(editing);
      Message.success('已新增');
    }
    editVisible.value = false;
    fetchList();
  } catch (error) {
    console.error('保存角色失败:', error);
    Message.error('保存失败，请重试');
  } finally {
    saving.value = false;
  }
}

async function onDelete(row: SysRole) {
  try {
    await roleDelete(row.roleId);
    Message.success('已删除');
    fetchList();
  } catch (error) {
    console.error('删除角色失败:', error);
    Message.error('删除失败，请重试');
  }
}

// 分配菜单相关代码保持不变
const assignVisible = ref(false);
const assignLoading = ref(false);
const assignSaving = ref(false);
const currentRoleId = ref<number | null>(null);
const menuTree = ref<SysMenu[]>([]);
const checkedMenuIds = ref<number[]>([]);

async function openAssignMenus(row: SysRole) {
  currentRoleId.value = row.roleId;
  assignVisible.value = true;
  assignLoading.value = true;
  try {
    const ml = await menuList();
    menuTree.value = Array.isArray(ml.data) ? ml.data : [];

    // 预选：尝试从 roleGet 获取已分配菜单
    try {
      const r = await roleGet(row.roleId);
      const ids: number[] = (r.data as any)?.menuIdList || [];
      checkedMenuIds.value = Array.isArray(ids) ? ids : [];
    } catch (error) {
      console.error('获取角色菜单失败:', error);
      checkedMenuIds.value = [];
    }
  } catch (error) {
    console.error('获取菜单列表失败:', error);
    Message.error('获取菜单列表失败');
  } finally {
    assignLoading.value = false;
  }
}

async function submitAssignMenus() {
  if (!currentRoleId.value) return;
  assignSaving.value = true;
  try {
    await roleAssignMenus(currentRoleId.value, checkedMenuIds.value);
    Message.success('已分配菜单');
    assignVisible.value = false;
  } catch (error) {
    console.error('分配菜单失败:', error);
    Message.error('分配菜单失败，请重试');
  } finally {
    assignSaving.value = false;
  }
}

onMounted(fetchList);
</script>

<style scoped>
.page-wrap { padding: 12px; }
</style>
